package com.beiing.tianshuai.tianshuai.freshnews.view;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.NewDiscoveryPublishActivity;
import com.beiing.tianshuai.tianshuai.adapter.FreshNewsRecyclerViewAdapter;
import com.beiing.tianshuai.tianshuai.anim.LikeAnimator;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.DiscoveryIsPraiseBean;
import com.beiing.tianshuai.tianshuai.entity.FreshNewsListBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.freshnews.presenter.DiscoveryPresenter;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.subscriptions.ArrayCompositeSubscription;

/**
 * 发现activity
 *
 * @author LZQ
 * @date 2017/7/6
 */
public class DiscoveryActivity extends BaseActivity implements DiscoveryViewImpl {

    @BindView(R.id.toolbar_tv_title)
    TextView toolbarTvTitle;
    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_iv_publish)
    ImageView toolbarIvPublish;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.news_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mSmtRefreshLayout;
    @BindView(R.id.refresh_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.refresh_footer)
    ClassicsFooter mRefreshFooter;

    private static final int PAGE_SIZE = 10;
    private static final String TAG = "DiscoveryActivity";
    private static boolean isPublished;
    private int page = 1;
    private int mPicNum = 10;
    private FreshNewsRecyclerViewAdapter mAdapter;
    private List<FreshNewsListBean.DataBean.FreshBean> mFreshBeanList;
    private List<FreshNewsListBean.DataBean.FreshBean> mFreshBeans;
    private boolean isFirstLoad = true;
    private boolean isLoadFinish;
    private DiscoveryPresenter mPresenter;
    private String uid;
    private RxBus rxBus;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_fresh_news;
    }

    @Override
    protected void init() {
        uid = UserInfoBean.getUid(mContext);
        initToolbar();
        initRecyclerView();
        setPresenter();
        initListener();
        initRxBus();
    }

    private void initToolbar() {
        toolbarTvTitle.setText("发现");
        toolbarIvBack.setVisibility(View.VISIBLE);
        toolbarIvPublish.setVisibility(View.VISIBLE);
    }

    public void setPresenter() {
        mPresenter = new DiscoveryPresenter(this);
        mPresenter.getDiscovery(uid, page, PAGE_SIZE, mPicNum, 0);
    }

    private void initRecyclerView() {
        mFreshBeanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mAdapter = new FreshNewsRecyclerViewAdapter(mFreshBeanList, mContext);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                ContextCompat.getColor(mContext, R.color.common_gray_background)));
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemViewClickListener(new FreshNewsRecyclerViewAdapter.OnItemViewClickListener() {
            @Override
            public void onItemViewClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.discovery_like:
                        mAdapter.setOnItemClickListener(null);
                        mPresenter.praiseDiscovery(uid, mFreshBeanList.get(position).getId());
                        break;
                    default:
                        mAdapter.setOnItemClickListener(new FreshNewsRecyclerViewAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                Intent intent = new Intent();
                                intent.setClass(mContext, DiscoveryDetailActivity.class);
                                intent.putExtra("position", position);
                                intent.putExtra("fresh_id", mFreshBeanList.get(position).getId());
                                startActivity(intent);
                            }
                        });
                }
            }

            //点赞事件
            @Override
            public void onLikeClick(View view, int position, FreshNewsListBean.DataBean.FreshBean bean,
                                    TextView tvAddOne) {
                uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mAdapter.setOnItemClickListener(null);
                    mPresenter.praiseDiscovery(uid, bean.getId());
                    boolean isLiked = bean.getIs_thing() == 1;
                    TextView likeView = (TextView) view;
                    Integer likeNum = Integer.valueOf(likeView.getText().toString());
                    if (isLiked) {
                        likeNum--;
                        LikeAnimator.disLikeAnimator(mContext, likeView);
                    } else {
                        likeNum++;
                        LikeAnimator.thumbAnimator(mContext, likeView);
                        LikeAnimator.addOneTextAnimator(mContext, tvAddOne);
                    }
                    likeView.setText(String.valueOf(likeNum));
                }
            }

            @Override
            public void onHeaderClick(View view, int position, FreshNewsListBean.DataBean.FreshBean bean) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", bean.getUserid());
                startActivity(intent);
            }

        });
    }

    private void initListener() {
        mSmtRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSmtRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));

        mSmtRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinish) {
                    mPresenter.getDiscovery(UserInfoBean.getUid(mContext), page, PAGE_SIZE, mPicNum, 0);
                } else {
                    mSmtRefreshLayout.finishLoadmore();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshData();
            }
        });

        toolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        toolbarIvPublish.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String uid = UserInfoBean.getUid(mContext);
                if (!TextUtils.isEmpty(uid)) {
                    String attestation = UserInfoBean.getAttestation(mContext);
                    switch (attestation) {
                        case "3":
                        case "4":
                            isPublished = true;
                            Intent intent = new Intent(mContext, NewDiscoveryPublishActivity.class);
                            intent.putExtra("type", 1);
                            startActivity(intent);
                            break;
                        case "2":
                        default:
                            showShortText("组织认证/企业认证”用户才可以发布噢~");
                            break;
                    }
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
            }
        });
    }

    private void refreshData() {
        page = 1;
        mPresenter.getDiscovery(UserInfoBean.getUid(mContext), page, PAGE_SIZE, mPicNum, 1);
        mRefreshHeader.onFinish(mSmtRefreshLayout, true);
    }

    @Override
    public void showProgress() {
        if (isFirstLoad) {
            CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
            isFirstLoad = false;
        }
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void showDiscovery(FreshNewsListBean.DataBean dataBean) {
        if (isFirstLoad) {
            mAdapter.notifyDataSetChanged();
            isFirstLoad = false;
        }
        mFreshBeans = dataBean.getFresh();
        int size = mFreshBeans.size();
        if (size == 0) {
            showShortText("已加载全部内容");
        } else if (size < PAGE_SIZE) {
            isLoadFinish = true;
            page++;
            mFreshBeanList.addAll(mFreshBeans);
            mAdapter.notifyDataSetChanged();
        } else {
            isLoadFinish = false;
            page++;
            mFreshBeanList.addAll(mFreshBeans);
            mAdapter.notifyDataSetChanged();
        }

        boolean isRefreshLayoutWorking = mSmtRefreshLayout != null &&
                (mSmtRefreshLayout.isRefreshing() || mSmtRefreshLayout.isLoading());
        if (isRefreshLayoutWorking) {
            mSmtRefreshLayout.finishRefresh();
            mSmtRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void refreshDiscovery(FreshNewsListBean.DataBean dataBean) {
        mFreshBeans = dataBean.getFresh();
        int size = mFreshBeans.size();
        if (size == 0) {
            showShortText("已加载全部内容");
        } else if (size < PAGE_SIZE) {
            isLoadFinish = true;
            page++;
            mFreshBeanList.clear();
            mFreshBeanList.addAll(mFreshBeans);
            mAdapter.notifyDataSetChanged();
        } else {
            isLoadFinish = false;
            page++;
            mFreshBeanList.clear();
            mFreshBeanList.addAll(mFreshBeans);
            mAdapter.notifyDataSetChanged();
        }

        boolean isRefreshWorking = mSmtRefreshLayout != null &&
                (mSmtRefreshLayout.isRefreshing() || mSmtRefreshLayout.isLoading());
        if (isRefreshWorking) {
            mSmtRefreshLayout.finishRefresh();
            mSmtRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void showIsPraised(DiscoveryIsPraiseBean isPraiseBean) {

    }

    @Override
    public void showError(int errorType) {
        switch (errorType) {
            case 0:
                showShortText("数据获取错误，请检查您的网络");
                mRefreshHeader.onFinish(mSmtRefreshLayout, false);
                boolean isRefreshLayoutWorking = mSmtRefreshLayout != null &&
                        (mSmtRefreshLayout.isRefreshing() || mSmtRefreshLayout.isLoading());
                if (isRefreshLayoutWorking) {
                    mSmtRefreshLayout.finishRefresh(false);
                    mSmtRefreshLayout.finishLoadmore(false);
                }
                break;
            case 1:
                break;
            case 2:
                showShortText("点赞失败");
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isPublished) {
            refreshData();
        }
        isPublished = false;
    }

    private void initRxBus() {
        rxBus = RxBus.getInstanceBus();
        registerRxBus(MsgEvent.class, new Consumer<MsgEvent>() {
            @Override
            public void accept(@NonNull MsgEvent msgEvent) {
                //根据事件类型进行处理
                if (TextUtils.equals(msgEvent.getType(), "点赞")) {
                    if ((int) msgEvent.getData() == 200) {
                        LogUtils.i("新鲜事详情点赞", "点赞成功");
                        int newThing = Integer.parseInt(mFreshBeanList.get(msgEvent.getPosition()).getPraise()) + 1;
                        mFreshBeanList.get(msgEvent.getPosition()).setPraise(newThing + "");
                        mFreshBeanList.get(msgEvent.getPosition()).setIs_thing(1);
                        mAdapter.notifyDataSetChanged();
                    } else if ((int) msgEvent.getData() == 201) {
                        int newThing = Integer.parseInt(mFreshBeanList.get(msgEvent.getPosition()).getPraise()) - 1;
                        mFreshBeanList.get(msgEvent.getPosition()).setPraise(newThing + "");
                        mFreshBeanList.get(msgEvent.getPosition()).setIs_thing(0);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    public <T> void registerRxBus(Class<T> eventType, Consumer<T> action) {
        Disposable disposable = rxBus.doSubscribe(eventType, action, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) {
                LogUtils.e(throwable.getMessage(), TAG);
            }
        });
        rxBus.addSubscription(this, disposable);
    }

    @Override
    protected void onDestroy() {
        //解注册rxBus防止内存泄漏
        rxBus.unSubscribe(this);
        super.onDestroy();
    }
}
